<?php

namespace IDock\Insurance\YAIC\Request;

use Exception;
use IDock\IDock\IDock;
use IDock\IDock\IDockEnums;
use IDock\Insurance\YAIC\Response\PremiumInquiryResponse;
use IDock\Insurance\YAIC\YAICEnums;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\Premium\PremiumRelationVisitor;

class PremiumInquiryRequest extends AllYAICRequest
{
    protected $route = '';

    protected $response = PremiumInquiryResponse::class;

    protected $urlTip = '报价接口';

    public $transCode = 'C2';

    /*** @var  PremiumInquiryVisitor $visitor */
    protected $visitor;

    public function generate(): array
    {
        $data = [
            'cityCode' => $this->visitor->getExtInfoVisitor()->argc['cityCode'] ?? '',
            'cityName' => $this->visitor->getExtInfoVisitor()->argc['cityName'] ?? '成都',
            'privy' => $this->getRelations(),
            'cars' => $this->getCarInfo(),
            'kinds' => $this->getKinds(),
            'extendInfo' => [
                'ExtendInfoDTO' => [
                    ['key' => 'matchCode', 'value' => $this->visitor->getExtInfoVisitor()->argc['matchCode'] ?? ''],
                    ['key' => 'agentHandlerCode', 'value' => $this->visitor->getExtInfoVisitor()->argc['agentHandlerCode'] ?? ''],
                    ['key' => 'agentHandlerName', 'value' => $this->visitor->getExtInfoVisitor()->argc['agentHandlerName'] ?? ''],
                    ['key' => 'agentCode', 'value' => $this->visitor->getExtInfoVisitor()->argc['agentCode'] ?? ''],
                    ['key' => 'agentName', 'value' => $this->visitor->getExtInfoVisitor()->argc['agentName'] ?? ''],
                    ['key' => 'agreementCode', 'value' => $this->visitor->getExtInfoVisitor()->argc['agreementCode'] ?? ''],
                    ['key' => 'certificateNo', 'value' => $this->visitor->getExtInfoVisitor()->argc['certificateNo'] ?? ''],
                ]
            ],
        ];
        if(!empty($this->visitor->getCiStartData())){
            $data['jqRiskCode'] = '039001';
            $data['jqStartDate'] = $this->visitor->getCiStartData();
            $data['jqEndDate'] = $this->visitor->getCiEndData();
        }
        if(!empty($this->visitor->getBiStartData())){
            $data['syRiskCode'] = '039002';
            if($this->visitor->isNewEnergy){
                $data['syRiskCode'] = '039011';
            }
            $data['syStartDate'] = $this->visitor->getBiStartData();
            $data['syEndDate'] = $this->visitor->getBiEndData();
        }
        if(!empty($this->visitor->chargingPileVisitorList) && $this->visitor->vehicleVisitor->isNewVehicle){
            $data['chargingPiles'] = $this->getChargingPiles();
        }
        if($this->visitor->ciStartData){
            $data['carTax'] = $this->getCarTax();
        }
        if($this->visitor->getNonCarInquiryVisitor()->getNonCarList())
        {
            $data['extendInfo']['ExtendInfoDTO'][] = ['key' => 'relatedProducts','value' => $this->getNonCar()];
        }
        return $data;
    }

    private function getNonCar()
    {
        /*** @var $single NonCarProductVisitor */
        $single = $this->visitor->getNonCarInquiryVisitor()->getNonCarList()[0];
        $nonCar = [
            'RationCode' => $single->planCode,
            'nocarRiskcode' => '',//非车险种代码
            'RationName' => $single->planname,
            'RationCode' => '',
        ];
    }

    private function getCarTax()
    {
        $arr = [
            'taxFlag' => YAICEnums::$taxTypeCode[$this->visitor->getCarTaxVisitor()->taxTypeCode] ?? '',
            'currentTaxDue' => [
                'AnnualTax' => [
                    'taxStartDate' => $this->visitor->carTaxVisitor->taxStartDate,
                    'taxEndDate' => $this->visitor->carTaxVisitor->taxEndDate,
                ],
            ]
        ];
        if($this->visitor->carTaxVisitor->taxTypeCode == 'T02'){
            $arr['currentTaxDue']['AnnualTax']['paid'] = [
                'taxDepartmentCode' => $this->visitor->carTaxVisitor->taxDepartmentCode,
                'taxDepartment' => $this->visitor->carTaxVisitor->taxDepartment,
                'taxDocumentNumber' => $this->visitor->carTaxVisitor->taxDocumentNumber,
                'taxDocumentDate' => $this->visitor->carTaxVisitor->taxDocumentDate,
                'taxPaidAreaCode' => $this->visitor->carTaxVisitor->taxPaidAreaCode,
            ];
        }
        if($this->visitor->carTaxVisitor->taxTypeCode == 'T03' or $this->visitor->carTaxVisitor->taxTypeCode == 'T04'){
            $arr['currentTaxDue']['AnnualTax']['deRate'] = [
                'noTaxCarType' => '3T2005',//免税车辆类型
                'deDuctiondueCode' => YAICEnums::$taxReductionReasonCode[$this->visitor->carTaxVisitor->taxReductionReasonCode],//
                'deDuctiondueType' => $this->visitor->carTaxVisitor->taxReductionCode,
                'deDuctionDocumentNumber' => $this->visitor->carTaxVisitor->taxDocumentNumber,
                'taxDepartmentDode' => $this->visitor->carTaxVisitor->taxDepartmentCode,
                'taxDepartment' => $this->visitor->carTaxVisitor->taxDepartment
            ];
            if($this->visitor->carTaxVisitor->taxReductionCode == 'P'){
                $arr['currentTaxDue']['AnnualTax']['deRate']['deDuctiondueProportion'] = $this->visitor->carTaxVisitor->taxFreeRate;
            }
            if($this->visitor->carTaxVisitor->taxReductionCode == 'A'){
                $arr['currentTaxDue']['AnnualTax']['deRate']['deDuction'] = $this->visitor->carTaxVisitor->taxExemption;
            }
        }
        return $arr;
    }

    private function getRelations()
    {
        $applicant = $this->getRelation($this->visitor->getApplicantVisitor());
        $applicant['insuredFlag'] = '1';
        $insured = $this->getRelation($this->visitor->getInsuredVisitor());
        $insured['insuredFlag'] = '2';
        return ['PrivyDTO' => [$applicant,$insured]];
    }

    private function getRelation(PremiumRelationVisitor $relationVisitor)
    {
        $relation = [
            'insuredName' => $relationVisitor->name,
            'insuredNature' => YAICEnums::$relationTypeCode[$relationVisitor->typeCode] ?? '',
            'identifyType' => YAICEnums::$certificateTypeCode[$relationVisitor->certificateTypeCode] ?? '',
            'identifyNumber' => $relationVisitor->certificateNo,
            'email' => $relationVisitor->email,
            'cresidaddr' => $relationVisitor->address,
            'provinceCode' => $relationVisitor->provinceCode,
            'province' => $relationVisitor->provinceName,
            'cityCode' => $relationVisitor->cityCode,
            'city' => $relationVisitor->cityName,
            'countyCode' => $relationVisitor->areaCode,
            'county' => $relationVisitor->areaName,
        ];
        if(empty($relation['identifyType'])){
            throw new \Exception("不支持该证件类型");
        }
        if($relationVisitor->typeCode == 'R1'){
            $relation['idcardStartDate'] = $relationVisitor->certificateStartDate;
            $relation['idcardEndDate'] = $relationVisitor->certificateEndDate;
            $relation['phoneNo'] = $relationVisitor->mobile;
            if(strlen($relationVisitor->certificateNo) == 18){
                $relation['birthDay'] = $this->getBirthday($relationVisitor->certificateNo);
                $relation['sex'] = $this->getGenderByIDCard($relationVisitor->certificateNo);
            }
            if($relationVisitor->certificateTypeCode == '99'){
                $relation['identifyType'] = '120009';
            }
        }
        if($relationVisitor->typeCode != 'R1'){
            $relation['incorporationDate'] = $relationVisitor->certificateStartDate;
            $relation['industryCategory'] = 'O8190';//其他未列明服务行业
            $relation['identificationNumber'] = $relationVisitor->certificateNo;
            $relation['scaleType'] = '3';// 企业规模 小型
            $relation['registeredCapital'] = '500';//注册资本
            $relation['socialFlag'] = '1';
            $relation['legalRepresentative'] = $relationVisitor->name;
            $relation['registeredAddress'] = $relationVisitor->address;
            $relation['enterprisePhoneNumber'] = $relationVisitor->mobile;
            $relation['contactName'] = $relationVisitor->linkManName ?: $relationVisitor->name;
            $relation['isBranchCom'] = '0';
            $relation['unitType'] = '9';
        }

        return $relation;
    }

    /**
     * 通过身份证获取性别
     * @param $idCard
     * @return string
     * @throws Exception
     */
    public function getGenderByIDCard($idCard): string
    {
        if(strlen($idCard) != 18){
            throw new Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard,16,1)) % 2;
        return $gender ? '1' : '2';
    }

    /**
     * @throws Exception
     */
    public function getBirthday($idCard): string
    {
        if(strlen($idCard) != 18){
            throw new Exception("身份证位数不合法");
        }
        return substr($idCard,6,4).'-'.substr($idCard,10,2).'-'.substr($idCard,12,2);
    }

    private function getCArInfo()
    {
        $vehicle = $this->visitor->vehicleVisitor;
        $car = [
            'queryModelNo' => $this->visitor->vehicleVisitor->argc['queryModelNo'] ?? '',
            'licenseNo' => $vehicle->licenseNo,
            'licenseType' => YAICEnums::$licenseTypeCode[$vehicle->licenseTypeCode] ?? '',
            'licenseColorcode' => YAICEnums::$licenseColorCode[$vehicle->licenseColorCode] ?? '',
            'frameNo' => $vehicle->vin,
            'engineNo' => $vehicle->engineNo,
            'enrollDate' => $vehicle->firstRegisterDate,
            'modelCode' => $vehicle->vehicleModelCode,
            'modelName' => $vehicle->vehicleModel,
            'carKindCode' => $this->getCarKindCode(),
            'vehicleType' => $vehicle->vehicleStyleCode,
            'useNatureCode' => YAICEnums::$causeType[$vehicle->causeType] ?? '',
            'seatCount' => $vehicle->vehicleSeat,
            'purchasePrice' => $vehicle->negotiatedValue ?: $vehicle->vehiclePrice,
//            'certificateDate' => $vehicle->carCertificateDate,
            'tonnage' => $vehicle->vehicleTonnage,
            'wholeWeight' => $vehicle->wholeWeight,
        ];
        if($vehicle->transferDate){
            if($vehicle->isCiTransfer){
                $car['transferDate'] = $vehicle->transferDate;
            }
            if($vehicle->isTransfer){
                $car['biTransferDate'] = $vehicle->transferDate;
            }
        }
        if($vehicle->carCertificateNo){
            $car['certificateNo'] = $vehicle->carCertificateNo;
        }
        return $car;
    }

    private function getCarKindCode(): string
    {
        $code = '';
        $seat = $this->visitor->getVehicleVisitor()->vehicleSeat;
        $carKind = $this->visitor->getVehicleVisitor()->carKindCode;
        $weight = round(intval($this->visitor->getVehicleVisitor()->vehicleTonnage) / 1000, 2);
        if ($carKind == '100') {
            //客车
            if ($seat < '6') {
                $code = '365001';
            } elseif ($seat < '10') {
                $code = '365002';
            } elseif ($seat < '20') {
                $code = '365003';
            } elseif ($seat < '36') {
                $code = '365004';
            } else {
                $code = '365005';
            }
        } elseif ($carKind == '200') {
            //货车
            if ($weight < '2') {
                $code = '365006';
            } elseif ($weight < '5') {
                $code = '365007';
            } elseif ($weight < '10') {
                $code = '365008';
            } else {
                $code = '365009';
            }
        }
        if (empty($code)) {
            throw new Exception("不支持的车辆种类");
        }
        return $code;
    }

    private function getKinds()
    {
        $coverageList = [];
        /*** @var PremiumCoverageVisitor $coverageVisitor */
        foreach ($this->visitor->getCoverageVisitorList() as $coverageVisitor) {

            $coverage = $coverageVisitor->coverageCode;


            $item = [
                'kindCode' => YAICEnums::$coverageCode[$coverage] ?? '',
                'kindname' => YAICEnums::$coverageName[$coverage],
                'quantity' => $coverageVisitor->quantity ?: 0,//
                'amount' => $coverageVisitor->amount,
                'unitAmount' => $coverageVisitor->unitAmount ?: $coverageVisitor->amount,
            ];
//            if(!empty($coverageVisitor->quantity)){
//                $item['quantity'] = $coverageVisitor->quantity;
//            }
            //乘客
            if(in_array($coverage,['C05002', 'C05003', 'C15002', 'C15003'])){
                $item['quantity'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
                $item['amount'] = intval($coverageVisitor->amount * $item['quantity']);
            }
            if(in_array($coverage,['C05001','C15001'])){
                $item['unitAmount'] = $coverageVisitor->unitAmount;
                $item['quantity'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
            }
            //修理期间
            if (in_array($coverage, ['C03003', 'C13003', 'C03004', 'C13004'])) {
                $item['unitAmount'] = $coverageVisitor->amount;
            }
            //绝对免赔率
            if (in_array($coverage, ['C02006', 'C03005', 'C04004', 'C05004', 'C12006', 'C13005', 'C14004', 'C15004'])) {
                $item['deductibleRatio'] = $coverageVisitor->deductionRate;
            }
            //特约
            if (in_array($coverage, ['C08001', 'C08002', 'C08003', 'C08004', 'C18001', 'C18002', 'C18003', 'C18004'])) {
                $item['serviceTimes'] = $coverageVisitor->serviceTimes;
            }
            //司机险
            if (in_array($coverage, ['C04001', 'C04002', 'C04003', 'C14001', 'C14002', 'C14003'])) {
                $item['unitAmount'] = $coverageVisitor->amount;
                $item['quantity'] = 1;
            }
            //剔除交强险代码
            if ($coverage == 'C01001') {
                unset($item['amount']);
                unset($item['unitAmount']);
            }
            $coverageList[] = $item;
        }
        return ['KindDTO' => $coverageList];
    }

    private function getChargingPiles()
    {
        $list = [];
        /*** @var PremiumChargingPileVisitor $premiumChargingPileVisitor */
        foreach ($this->visitor->chargingPileVisitorList as $premiumChargingPileVisitor) {
            $item = [
                'serialNo' => $premiumChargingPileVisitor->seqNo,
                'chargingModel' => $premiumChargingPileVisitor->chargingPileType,
                'chargingNum' => $premiumChargingPileVisitor->chargingPileCode,
                'chargingAddr' => $premiumChargingPileVisitor->chargingPileAddress,
                'chargingAge' => YAICEnums::$chargingPileYearLimit[$premiumChargingPileVisitor->chargingPileYearLimit] ?? '',
                'chargingType' => YAICEnums::$chargingPileKind[$premiumChargingPileVisitor->chargingPileKind] ?? '',
                'chargingAddrType' => YAICEnums::$chargingPileAddressType[$premiumChargingPileVisitor->chargingPileAddressType] ?? ''
            ];
            $list[] = $item;
        }
        return $list;
    }
}
